package org.csu.jpetstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.csu.jpetstore.bo.ItemBO;
import org.csu.jpetstore.entity.Inventory;
import org.csu.jpetstore.entity.Item;
import org.csu.jpetstore.mapper.InventoryMapper;
import org.csu.jpetstore.mapper.ItemMapper;
import org.csu.jpetstore.service.ItemService;
import org.csu.jpetstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    private ProductService productService;

    @Override
    public List<ItemBO> getItemListByProductId(String productId) {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        List<Item> itemList = itemMapper.selectList(queryWrapper);
        List<ItemBO> itemBOList = new ArrayList<>();
        for (Item item : itemList) {
            itemBOList.add(ItemBO.toItemBO(productService.getProduct(productId).getCategoryId(), item,
                    inventoryMapper.selectById(item.getItemId())));
        }
        return itemBOList;
    }

    @Override
    public Item getItemByItemId(String itemId) {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("item_id", itemId);
        return itemMapper.selectById(itemId);
    }

    /**
     * 通过itemId获取ItemBO
     *
     * @param itemId itemId
     * @return ItemBO
     * @author huangzhangyan
     * @date 2022/4/13 20:45
     */
    @Override
    public ItemBO getItemBOById(String itemId) {

        return ItemBO.toItemBO(productService.getProduct(itemMapper.selectById(itemId).getProductId()).getCategoryId()
                , itemMapper.selectById(itemId), inventoryMapper.selectById(itemId));
    }

    @Override
    public void updateInventoryQuantity(String itemId, Integer quantity) {
        UpdateWrapper<Inventory> updateWrapper = new UpdateWrapper<>();
        int totalQuantity = inventoryMapper.selectById(itemId).getQuantity();
        updateWrapper.eq("item_id", itemId).set("quantity", totalQuantity - quantity);
        inventoryMapper.update(null, updateWrapper);
    }
}
